package com.yanqu.road.server.channelserver.webservice;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import com.yanqu.road.server.webservice.GrossWebService;
import com.yanqu.road.utils.net.ChannelNetConfigHelper;
import com.yanqu.road.utils.net.ServerNetConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.xml.ws.Endpoint;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChannelWebServiceHelper {

    private static Logger logger = LogManager.getLogger(ChannelWebServiceHelper.class.getName());

    private static ChannelWebServiceHelper gameWebService;

    private ChannelWebServiceHelper() {
    }

    public synchronized static ChannelWebServiceHelper getInstance() {
        if (gameWebService == null) {
            gameWebService = new ChannelWebServiceHelper();
        }

        return gameWebService;
    }

    public boolean start(int serverType) {
        ServerNetConfig webXml = ChannelNetConfigHelper.getNetConfigXml(serverType, 0);

        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(webXml.getAdminPort()), 0);
            ExecutorService threads = Executors.newFixedThreadPool(20);
            server.setExecutor(threads);
            server.start();

            Endpoint castleEndpoint = Endpoint.create(new ChannelWebService());
            HttpContext castleContext = server.createContext("/channelws");
            castleEndpoint.publish(castleContext);

            return true;
        } catch (IOException e) {
            logger.error("ChannelWebService init error", e);
        }

        return false;
    }
}
